package org.activemonitoring.datastore.jms;

import java.util.Date;
import java.util.List;

import org.activemonitoring.datastore.dao.DataStoreDao;
import org.activemonitoring.datastore.entity.MeasureEntity;
import org.activemonitoring.datastore.jms.client.DataStoreJmsClient;
import org.activemonitoring.domain.Measure;
import org.activemonitoring.domain.Measures;
import org.activemonitoring.harvesters.HarvesterImplCase;
import org.apache.log4j.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import static org.junit.Assert.assertEquals;

public class DataStoreJmsCase {

    private static final Logger logger = Logger.getLogger(HarvesterImplCase.class);

    private ClassPathXmlApplicationContext applicationContext;
    private DataStoreJmsClient dataStoreJmsClient;
    private DataStoreDao dataStoreDao;

    @Before
    public void setUp() {
        this.applicationContext = new ClassPathXmlApplicationContext(new String[] {
                "applicationContext-harvesters.xml", "applicationContext-datastore.xml",
                "applicationContext-test-jms.xml" });
        this.applicationContext.start();
        this.dataStoreDao = this.applicationContext.getBean("dataStoreDao", DataStoreDao.class);
        this.dataStoreJmsClient = this.applicationContext.getBean("dataStoreJmsClient", DataStoreJmsClient.class);
    }

    @Test
    public void testSendMeasuresViaJms() throws Exception {
        this.dataStoreDao.clear();

        Measure measure = new Measure();
        measure.setModuleName("Test");
        measure.setName("testClientPostMeasure");
        measure.setCorrelationId("Test-987654321-123456789");
        long time = new Date().getTime();
        measure.setStartTime(time - 1000L);
        measure.setEndTime(time);
        Measures measures = new Measures();
        measures.getMeasure().add(measure);
        measures.getMeasure().add(measure);
        this.dataStoreJmsClient.store(measures);

        Thread.sleep(500L);

        List<MeasureEntity> loadedMeasures = this.dataStoreDao.getMeasures();
        assertEquals(2, loadedMeasures.size());
        long totalTime = 0;
        for (MeasureEntity measureEntity : loadedMeasures) {
            totalTime += measureEntity.getElapsedTime();
        }
        logger.info("Average elapsed time: " + totalTime / loadedMeasures.size() + " ms");
    }

    @After
    public void tearDown() {
        this.dataStoreDao.clear();
        this.applicationContext.stop();
    }
}
